package com.coolwen.controller;

import com.coolwen.entity.LoginUser;
import com.coolwen.entity.User;
import com.coolwen.entity.UserException;
import com.coolwen.service.LoginService;
import com.coolwen.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;

import org.springframework.http.HttpRequest;

/**
 * Created by user on 2016/5/4.
 */
@Controller
@RequestMapping("/login")
public class LoginController {

    @Autowired
    LoginService loginService;

    @RequestMapping(value = "/do_login", method = RequestMethod.GET)
    public String login(Model model) {
//        LoginUser loginUser=new LoginUser();
        model.addAttribute(new LoginUser());
        return "login/login";
    }

    @RequestMapping(value = "/do_login", method = RequestMethod.POST)
    public String login(@Validated LoginUser user, BindingResult br, HttpSession session) {
        if (br.hasErrors()) {
            //如果有错误直接跳转到add视图
            return "login/login";
        }
        String loginName = user.getLoginName();
        String loginPassword = user.getLoginPassword();
        System.out.print(user.getLoginName() + "---------" + user.getLoginPassword());
        if (loginService.selectByLoginUserName(loginName) == null || !loginService.selectByLoginUserName(loginName).getLoginPassword().equals(loginPassword)) {
            throw new UserException("用户名和密码错误！");
        }

        session.setAttribute("loginUser", loginService.selectByLoginUserName(loginName));
        return "redirect:/user/users";
    }

    /**
     * 局部异常处理,仅仅只能处理这个控制器中的异常！需要处理全部需要在spring-mvc.xml中配置
     *
     *
     */
//    @ExceptionHandler(value = {UserException.class})
//    public String handlerException(UserException e,HttpServletRequest req){
//        req.setAttribute("e",e);
//        return "error";
    //   }
}
